import { defineStore } from "pinia";
import EquityMallAPI from "@/api/equitymall";

export const useEquityMallStore = defineStore("equitymall", () => {
  // 使用 useStorage 存储所有规格选项
  const allSpecOptionsObj = useStorage<Record<string, SpecData[]>>("allSpecOptions", {});

  // 获取属性规格
  const handleSpecLoad = async (ids: number[]): Promise<SpecData[]> => {
    try {
      const res: any = await EquityMallAPI.getProductSpecByTagIds({
        tagIds: ids,
        pageNum: 1,
        pageSize: 10000,
      });
      return res.map((item: any) => ({
        id: item.id,
        name: item.name,
        specTagId: item.specTagId,
      }));
    } catch (error) {
      console.error("Error loading spec data:", error);
      return []; // 在出错时返回空数组，确保返回值始终是数组
    }
  };

  // 设置所有规格选项
  const setAllSpecOptionsObj = (data: SpecData[]): void => {
    allSpecOptionsObj.value = {};
    data.forEach((item) => {
      if (!allSpecOptionsObj.value[item.specTagId]) {
        allSpecOptionsObj.value[item.specTagId] = [];
      }
      allSpecOptionsObj.value[item.specTagId].push(item);
    });
  };
  const getAllSpecOptionsObj = () => {
    return allSpecOptionsObj.value;
  };
  return {
    allSpecOptionsObj,
    handleSpecLoad,
    setAllSpecOptionsObj,
    getAllSpecOptionsObj,
  };
});

export function useEquityMallStoreHook() {
  return useEquityMallStore();
}

interface SpecData {
  id: number;
  name: string;
  specTagId: number;
}
